﻿Imports System
Imports System.Windows
Imports System.Windows.Media.Animation



Public Class GameLoop
    Protected _lastTick As DateTime
    Public Delegate Sub UpdateHandler(ByVal elapsed As TimeSpan)
    Public Event Update As UpdateHandler
    Private gameLoop As Storyboard
    Protected stopped As Boolean

    Public Sub New(ByVal parent As FrameworkElement)
        Me.New(parent, 0)

    End Sub

    Public Sub New(ByVal parent As FrameworkElement, ByVal storyBoardMilliseconds As Double)
        gameLoop = New Storyboard()
        gameLoop.Duration = TimeSpan.FromMilliseconds(storyBoardMilliseconds)
        gameLoop.SetValue(FrameworkElement.NameProperty, "gameloop")
        parent.Resources.Add("gameloop", gameLoop)
        AddHandler gameLoop.Completed, AddressOf gameLoop_Completed
    End Sub

    Private Sub gameLoop_Completed(ByVal sender As Object, ByVal e As EventArgs)
        If stopped Then
            Exit Sub
        End If
        Tick()
        TryCast(sender, Storyboard).Begin()
    End Sub

    Public Sub Tick()
        Dim now As DateTime = DateTime.Now
        Dim elapsed As TimeSpan = now - _lastTick
        _lastTick = now
        RaiseEvent Update(elapsed)
    End Sub

    Public Sub Start()
        stopped = False
        If gameLoop IsNot Nothing Then
            gameLoop.Begin()
        End If
        _lastTick = DateTime.Now
    End Sub

    Public Sub [Stop]()
        stopped = True
    End Sub
End Class
